package pub.tbc.rubbish.client.util;

import lombok.extern.slf4j.Slf4j;
import pub.tbc.toolkit.Objs;
import pub.tbc.toolkit.PropsUtil;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * @author tbc on 2016/12/6 13:14:56.
 */
@Slf4j
public class IPHelper {

    private final String DEFAULT_IP_V4 = "127.0.0.1";

    public String getIPv4() {
        return getIPv4ByConfig();
    }

    private String getIPv4ByConfig(String... defaultIp) {
        // rubbish.properties
        return PropsUtil.getString(PropsUtil.load("rubbish.properties"), "service.ipv4", getIPv4Auto());
    }

    private String getIPv4Auto() {
        log.debug("自动获取IPv4地址...");
        String ip = DEFAULT_IP_V4;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("获取主机地址失败：" + e.getMessage());
            Arrays.stream(e.getStackTrace()).forEach(System.out::println);
        }
        return ip;
    }
}
